package user

import (
	"errors"
	"fmt"
	"gorm-demo/global"
	"gorm-demo/model"
	"gorm-demo/model/dto"
	"gorm-demo/utils"
	"gorm.io/gorm"
	"log"
	"time"
)

func LoginService(username string, password string) (string, error) {
	var user model.User
	tx := global.DB.Where("username = ?", username).First(&user)
	if tx.Error != nil {
		log.Default().Println(tx.Error)
		return "", errors.New("用户名或密码错误")
	}
	if user.ID == 0 {
		return "", errors.New("用户名或密码错误")
	}
	if !utils.Match(user.Password, password) {
		return "", errors.New("用户名或密码错误")
	}
	//创建token返回
	token, err := utils.NewToken(1, time.Hour*24)
	if err != nil {
		return "", errors.New("登录失败")
	}
	return token, nil
}

func GetPermissionTreeByUid(id int) dto.PermissionList {
	var tree model.User
	global.DB.Preload("Roles", func(db *gorm.DB) *gorm.DB {
		return db.Select("id, name").Preload("Permissions", func(db *gorm.DB) *gorm.DB {
			return db.Select("id, name")
		})
	}).Where("id=?", id).First(&tree)
	var rsts dto.PermissionList
	for _, role := range tree.Roles {
		rsts.Roles = append(rsts.Roles, role.Name)
		for _, permission := range role.Permissions {
			rsts.Permissions = append(rsts.Permissions, permission.Name)
		}
	}
	return rsts
}

func AddUser(username string, password string) error {
	var user model.User
	global.DB.Where("username = ?", username).First(&user)
	if user.ID != 0 {
		return errors.New(fmt.Sprintf("%v 用户已存在", username))
	}
	user.Username = username
	user.Password = password
	user.Roles = []model.Role{
		{
			Model: gorm.Model{ID: 4},
		},
	}
	err := global.DB.Create(&user).Error
	return err
}

func GetPermissionByToken(token string) *dto.PermissionList {
	var user model.User
	id, _ := utils.GetUserId(token)
	global.DB.Preload("Roles", func(db *gorm.DB) *gorm.DB {
		return db.Select("id, name").Preload("Permissions")
	}).Where("id=?", id).First(&user)
	var permissionList dto.PermissionList
	for _, role := range user.Roles {
		permissionList.Roles = append(permissionList.Roles, role.Name)
		for _, permission := range role.Permissions {
			permissionList.Permissions = append(permissionList.Permissions, permission.Name)
		}
	}
	return &permissionList
}
